<?php
/**
* 2017年3月16日
* 微信接口类
*/
class WeixinApi_model extends MY_Model
{
	   private $template_id = 'yxLqCNVFzqz0nKNDCUFfHhrF5_q-OaRqHh4yf25FWdE';

  	function __construct()
  	{
  		parent::__construct();
      // $this->load->view('Token_model','token');
  		//定义微信参数常量
  		$where = array(
        'id'=>1,
        );
      //$info = $this->myQueryOne('info',$where);
  		//define('appid',$info['appid']);
  		//define('appsecret',$info['appsecret']);
  		//define('mch_id',$info['mch_id']);
  		//define('key',$info['key']);
      //defined('appid') or define('appid',$info['appid']);
     // defined('appsecret') or define('appsecret',$info['appsecret']);
      //defined('mch_id') or define('mch_id',$info['mch_id']);
      //defined('key') or define('key',$info['key']);
  	}

    /**
   * 跳转获取code 用户授权 不管是否关注
   * @return [type] [description]
   */
    public function getCode(){
      $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".appid."&redirect_uri=http%3A%2F%2F".$_SERVER['SERVER_NAME']."%2FWeixin%2FLogin%2FweixinLoginBack&response_type=code&scope=snsapi_userinfo&state=23edsd32defewfeefewf#wechat_redirect";
      //print_r($url);die();
      redirect($url);
    }

     /**
     * 跳转获取code 用户授权 微信分享
     * @return [type] [description]
     */
     public function getCode_share(){
       $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".appid."&redirect_uri=http%3A%2F%2F".$_SERVER['SERVER_NAME']."%2FWeixin%2FEnter%2FweixinShareLoginBackfx&response_type=code&scope=snsapi_base&state=23edsd32defewfeefewf#wechat_redirect";
       redirect($url);
    }


  	/**
  	 * 微信接口获取token
  	 * @return [type] [description]
  	 */
  	function getToken(){
  		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.appid.'&secret='.appsecret;
  		$token = $this->httpGet($url);
  		return $token['access_token'];
  	}

    /**
     * get方式发送curl请求
     * @return [type] [description]
     */
    function httpGet($url){
      //初始化一个curl会话
      $ch = curl_init();
      //设置访问路径
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
      curl_setopt($ch, CURLOPT_TIMEOUT, 500);
      //运行
      $result = curl_exec($ch);
      if(curl_errno($ch)){
             return 'Errono'.curl_error($ch);
        } 
      curl_close($ch);
      
      return json_decode($result,true);
    }

		/**
     * @abstract 公众号查询菜单高级接口
     * @param 公众号 string $gh_num
     * @return jsonString $menu
     */
    public function query_menu() {   
        //API地址 
             
        $token = $this->getAccessToken();

        $url = sprintf("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s",$token);
        //返回菜单
        $menu = $this->httpGet($url);
        
        return  $menu;
    }
 		/**
     * @abstract 公众号创建菜单高级接口
     * @param 公众号 string $gh_num
     * @param 菜单 array $menu
     */
    public function create_menu($menu) {  
      $this->load->model('Curl_model','curl'); 
      $token = $this->getAccessToken();
     
      $menu = $this->json_encode_zhcn($menu);
      
      $url = sprintf("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s",$token);
      return $this->curl->https_post($url, $menu);
    }
    /**
     * @abstract 发送中文消息，中文消息编码
     * @param mixed $data
     * @return string
     */
    function json_encode_zhcn($data){
        return preg_replace('/\\\u([0-9a-f]{4})/ie', "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", json_encode($data));
    }

     /**
    * @abstract 获取access_token
    * @param  [type] $code [description]
    * @return [type]       [description]
    */
    static function get_access_token($code){  
      $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".appid."&secret=".appsecret."&code=".$code."&grant_type=authorization_code";  

      $data=$this->httpGet($url);//这个地方不能用file_get_contents    
      if( $data['access_token'] ){
        $_SESSION['access_token'] = $data['access_token'];
        return $data;
      }else{  
          // return "获取access_token错误";  
          return $data;
      }         
    }
    
   
    /**
     * @abstract 拉取用户信息 不包括关注信息
     * @param  [type] $code [description]
     * @return [type]       [description]
     */
    public function get_user($code){
      $data = self::get_access_token($code);
      if($data['access_token']){
        //拉取用户信息
        $user_res = self::get_user_info($data);
        return $user_res;
      }
      return false;
    }
   
    /**
     * @abstract 拉取用户信息
     */
    static function get_user_info($res){
      $url="https://api.weixin.qq.com/sns/userinfo?access_token=".$res['access_token']."&openid=".$res['openid']."&lang=zh_CN";  
      
      $data=$this->httpGet($url);//这个地方不能用file_get_contents   
      
      if($data['openid']){
          return $data;
      }else{
          return "拉取用户信息失败";
      }
    }



    /**
     * @abstract 获取用户详细信息 包括关注 用户必须关注 
     */
    function get_userinfo_all($code){
      $this->load->model('Token_model','token');
      $data = $this->get_access_token($code);
      $openid = $data['openid'];
      $token = $this->token->getAccessToken();//微信票据的access_token
      $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
      $user_info = json_decode(file_get_contents($url),true);
      return $user_info;  
    }



    /**
     * @abstract 获取所有关注该微信的 用户openid  关注者数量超过10000时 next_openid：最后一条数据 下一次调用
     */
    function get_weixinList($next='a'){
      $this->load->model('Token_model','token');
      $token = $this->token->getAccessToken();//微信票据的access_token
      if($next=='a'){
          //第一次下来的数据
          $user_list=json_decode(file_get_contents(sprintf('https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s',$token)),TRUE); 
      }else{
          //10000条之后的数据
          $user_list=json_decode(file_get_contents(sprintf('https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s',$token,$next)),TRUE); 
      }
      
      return $user_list;  
    }

    /**
     * 发送微信模板消息
     * @DateTime 2017-08-18
     * @author zyl
     * @param    [type]     $openid [用户openID]
     * @param    [type]     $link   [点击消息跳转地址]
     * @param    [type]     $data   [消息信息]
     * @return   [type]             [description]
     */
   public function send_template_msg($openid,$link,$data)
   {
      $this->load->model('Token_model','token');
      $token = $this->token->getAccessToken();//微信票据的access_token

      $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";

      $main_body = array(
          'touser'      =>  $openid,
          'template_id' =>  $this->template_id,
          "url" => $link,
          "data" => $data,
        );
      //加载curl工具模型
      $this->load->model('Curl_model','curl');

      $return = $this->curl->https_post($url,json_encode($main_body));
   }
   
}